package com.common.utils;

import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.print.attribute.standard.MediaSize;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Optional;

public class RequestUtil {

    public static HttpServletRequest getRequest() {
        return Optional.ofNullable(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())).orElseThrow(() -> new RuntimeException("未获取到当前请求信息")).getRequest();
    }

    public static String getUserId(){
        return getRequest().getHeader("userId");
    }

    public static String getUserAgent(){
        return getRequest().getHeader("User-Agent");
    }

    public static String getRoleId(){
        return getRequest().getHeader("roleId");
    }

    public static boolean  cookieExist(){
        Cookie[] cookies = getRequest().getCookies();
        if (cookies == null) {
            return false;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("authentication")) {
                return  true;
            }
        }
        return false;
    }

    public static String getLoginUserId(){
        String userId = getUserId();
        if (StringUtils.isEmpty(userId)) {
            throw new IllegalArgumentException("未登录");
        }
        return userId;
    }

    public static String getLoginUserName(){
        String username = getHeadKey("username");
        if (StringUtils.isEmpty(username)) {
            username = "Undefined";
        }
        return username;
    }

    /**
     * 获取Key获取Value
     * @return String
     */
    public static String getHeadKey(String key) {
        String value = RequestUtil.getRequest().getHeader(key);
        if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("无法获取"+key);
        }
        return value;
    }


    public static String getTokenId(){
        String value = RequestUtil.getRequest().getHeader("token");
        if (StringUtils.isEmpty(value)) {
            throw new RuntimeException("无法获取token");
        }
        return value;
    }

//    public static User getUserId(UserService userService){
//        String value = RequestUtil.getRequest().getHeader("userId");
//        if (StringUtils.isEmpty(value)) {
//            throw new RuntimeException("无法获取userId");
//        }
//        return  userService.getUserById(value);
//    }
}

